/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode *l = new ListNode;
        ListNode *head = l;
        l->val = 0;
        l->next = NULL;
        while(l1 != NULL && l2 != NULL){
            int t = l1->val + l2->val;
            if(t >= 10){
                t = t-10;
                l->val = l->val + t;
                ListNode *ln = new ListNode;
                ln->val = 1;
                l->next = ln;
            }
            else {
                l->val = l->val + t;
                if(l->val >= 10){
                    l->val = l->val - 10;
                    ListNode *ln = new ListNode;
                    ln->val = 1;
                    l->next = ln;
                }else{
                    if(l1->next != NULL || l2->next != NULL){
                        ListNode *ln = new ListNode;
                        ln->val = 0;
                        l->next = ln;
                    }
                }
            }
            l1 = l1->next;
            l2 = l2->next;
            l = l->next;
        }
        if(l1 != NULL){
            while(l1 != NULL){
                l->val = l->val + l1->val;
                if(l->val >= 10){
                    l->val = l->val - 10;
                    ListNode *ln = new ListNode;
                    ln->val = 1;
                    l->next = ln;
                }else{
                    if(l1->next != NULL){
                        ListNode *ln = new ListNode;
                        ln->val = 0;
                        l->next = ln;
                    }
                }
                l1 = l1->next;
                l = l->next;
            }
        }
        if(l2 != NULL){
            while(l2 != NULL){
                l->val = l->val + l2->val;
                if(l->val >= 10){
                    l->val = l->val - 10;
                    ListNode *ln = new ListNode;
                    ln->val = 1;
                    l->next = ln;
                }else{
                    if(l2->next != NULL){
                        ListNode *ln = new ListNode;
                        ln->val = 0;
                        l->next = ln;
                    }
                }
                l2 = l2->next;
                l = l->next;
            }
        }
        return head;
    }
};
